package com.hjy.serivce;

import com.hjy.entity.Permission;
import com.hjy.entity.Role;
import com.hjy.entity.Users;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 验证授权类
 */

public class AuthRealm extends AuthorizingRealm {

    @Autowired(required = false)
    private UsersService usersService;

    //授权(每次验证权限或角色都会走这个方法)
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //从session里面获取当前用户
        Users users=(Users) principalCollection.fromRealm(this.getClass().getName()).iterator().next();
        //存放给info添加所有关系集合
        List<String> permissionList=new ArrayList<>();
        //所有角色集合
        Set<Role> roleSet=users.getRoles();
        //存放给info添加的角色集合
        List<String> roleNameList=new ArrayList<>();
        //判断角色是否为空
        if (CollectionUtils.isNotEmpty(roleSet)){
            for (Role role : roleSet){
                //获取所有角色信息后添加进集合(存放到info)
                roleNameList.add(role.getRname());
                //获取所有关系集合
                Set<Permission> permissionSet=role.getPermissions();
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(permissionSet)){
                    for (Permission permission:permissionSet){
                        //获取所有权限后添加进集合
                        permissionList.add(permission.getName());
                    }
                }
            }
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermissions(permissionList);
        info.addRoles(roleNameList);
        System.out.println("授权");
        return info;
    }

    //认证登陆
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) authenticationToken;
        String username=usernamePasswordToken.getUsername();
        Users users=usersService.findByUsersName(username);
        System.out.println("登陆");
        return new SimpleAuthenticationInfo(users,users.getPassword(),this.getClass().getName());
    }

    public UsersService getUsersService() {
        return usersService;
    }

    public void setUsersService(UsersService usersService) {
        this.usersService = usersService;
    }
}
